<template>
  <div>
    <div class="app-container clearfix pageHeader">
      <div class="header fl">{{$route.meta.title}}</div>
    </div>
    <div class="app-container margin-content padding-content">
      <div class="clearfix">
        <div class="btn-wrapper fl">
          <el-button icon="el-icon-edit" type="primary" @click="handleCreate()">新建用户</el-button>
          <el-button icon="el-icon-delete" type="danger" @click="delUsers">删除</el-button>
        </div>
        <div class="fr">
          <el-form :model="query" inline>
            <el-form-item>
              <treeselect placeholder="请选择机构"
                          v-model="query.orgId"
                          :multiple="false"
                          :options="computedOptions"
                          @input="handleSelected"
                          :clearable=false
                          :load-options="loadOrgsOptions"
                          style="width: 150px">
                <label :title="node.label"
                       slot="option-label"
                       slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                       :class="labelClassName">
                  {{ node.label }}
                </label>
              </treeselect>
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="请输入用户名"
                v-model="query.name"
                @keyup.native="doSearchUsers">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-form-item>
            <!--<el-form-item>-->
            <!--<el-button @click="doSearch" icon="el-icon-search" type="primary">搜索</el-button>-->
            <!--<el-button @click="handleSearch">高级搜索</el-button>-->
            <!--</el-form-item>-->
          </el-form>
        </div>
      </div>

      <el-table
        :key="tableKey"
        :data="tableData"
        v-loading="listLoading"
        element-loading-text="正在加载..."
        style="width: 100%"
        :height="scrollHeight"
        @selection-change="handleSelectionChange">

        <el-table-column
          type="selection"
          width="55"
          :selectable="selectable">
        </el-table-column>
        <el-table-column label="用户名" min-width="120px" fixed="left">
          <template slot-scope="scope">
            <!--<span >{{scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}')}}</span >-->
            <span>{{scope.row.loginName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="150px">
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column width="100px" label="所属机构">
          <template slot-scope="scope">
            <span>{{scope.row.orgName}}</span>
          </template>
        </el-table-column>
        <el-table-column width="150px" label="邮箱">
          <template slot-scope="scope">
            <span>{{scope.row.email}}</span>
          </template>
        </el-table-column>
        <el-table-column width="100px" label="电话">
          <template slot-scope="scope">
            <span>{{scope.row.tel}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="200px"
                         class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <!--<a href="javascript:void(0)" @click="handleDetail(scope.row.id)" >详情</a > |-->
            <a href="javascript:void(0)" @click="$refs.passwordDialog.handleCreate(scope.row.id)">修改密码</a>
            <divider v-if="scope.row.loginName !== 'system'" type="vertical"></divider>
            <a href="javascript:void(0)" @click="handleEdit(scope.row.id)"
               v-if="scope.row.loginName !== 'system'">编辑</a>
            <divider v-if="scope.row.loginName !== 'system'" type="vertical"></divider>
            <a v-if="scope.row.loginName !== 'system'" href="javascript:void(0)" @click="delUsers(scope.row.id)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container align-right">
        <el-pagination background
                       :current-page="query.pageNum"
                       v-if="isPaging"
                       :page-size="query.pageSize"
                       :total="total"
                       @current-change="handleCurrentChange"
                       layout="total,prev, pager, next, jumper">
        </el-pagination>
      </div>
    </div>
    <!--新建用户对话框-->
    <user-dialog ref="userDialog" @submited-user="submitedUser" :menusOptions="orgianlData"></user-dialog>
    <password-dialog ref="passwordDialog" @submited-user="submitedPassword"
                     :menusOptions="orgianlData"></password-dialog>
  </div>
</template>

<script>
  import { getUsers, delUsers } from '@/api/users'
  import { getOrgTree } from '@/api/orgs'
  import { modifyObj } from '@/utils/tools'
  import { covertArrParams } from '@/utils/tools'
  import UserDialog from './components/newUserDialog'
  import passwordDialog from './components/editPasswordDialog'
  import Treeselect from '@riophae/vue-treeselect'
  import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
  import Divider from '@/components/Divider'

  export default {
    name: 'usersMain',
    components: {UserDialog, Treeselect, Divider, passwordDialog},
    computed: {
      computedOptions() {
        return modifyObj(this.optionsOrgs)
      }
    },
    data() {
      return {
        tableSelection: [],
        total: 0,
        dialogFormVisible: false,//新建用户窗口显隐属性
        dialogSearchFormVisible: false,//高级搜索窗口显隐属性
        listLoading: false,//列表加载开关
        orgianlData: null,
        sortOptions: [{label: 'ID Ascending', key: 0}],//下拉选择的数据源
        tableKey: 0,//表格key
        tableData: null,//表格的数据
        optionsOrgs: [],
        scrollHeight: null,
        isPaging: true,
        query: {
          loginName: '',
          pageNum: 1,
          pageSize: 20,
          orgId: '-1'
        },
        saveSetTimeoutSearch: null
      }
    },
    created() {
      this.getUserList(this.query) //获取用户列表
      this.getOrgTree() //获取机构树选项
      this.tableResize()
    },
    mounted() {

    },
    destroyed() {
    },
    methods: {
      tableResize(){
        const _height = 315
        this.scrollHeight = document.body.scrollHeight - _height
        window.onresize = () => {
          this.scrollHeight = document.body.scrollHeight - _height
        }
      },
      selectable(row){
        if (row.loginName !== 'system') {
          return true
        }
      },
      getOrgTree() {
        getOrgTree().then(res => {
          res = res.data
          let _arr = res.data
          _arr.unshift({
            name: '全部机构',
            label: '全部机构',
            id: -1
          })
          this.optionsOrgs = _arr
        })
      },
      loadOrgsOptions({action, parentNode, callback, id}) {
        callback()
      },
      handleSelected(value) {
        this.getUserList(this.query)
      },
      resetQuery() {
        this.query = {
          loginName: '',
          pageNum: 1,
          pageSize: 20,
          orgId: -1
        }
      },
      //打开新建用户
      handleCreate() {
        this.$refs.userDialog.handleCreate()
      },
      //打开编辑用户
      handleEdit(id) {
        this.$refs.userDialog.handleEdit(id)
      },
      //打开高级搜索
      handleSearch() {
        this.dialogSearchFormVisible = true;
      },
      //执行搜搜
//      doSearch(){
//        this.getUserList(this.query)
//      },
      //打开详情
//      handleDetail(id){
//        this.$parent.changeView(1, id)
//      },
      //获取用户列表
      getUserList(paramObj) {
        this.listLoading = true
        if (parseInt(paramObj.orgId) === -1) {
          paramObj = Object.assign({}, paramObj, {orgId: ''})
        }
        getUsers(paramObj).then(res => {
          this.listLoading = false
          res = res.data
          this.tableData = []
          this.tableData = res.data.dataList
          this.total = res.data.total
        })
      },
      /**
       * 翻页改变时候触发
       **/
      handleCurrentChange(val) {
        this.query.pageNum = val
        this.getUserList(this.query)
      },
      /**
       * 重置添加用户对话框表单
       */
      resetDataForm(formName) {
        this.$refs[formName].resetFields()
      },
      /**
       * 关闭创建用户对话框
       */
      closeAddUserDialog() {
//        this.resetDataForm('dataForm')
//        this.dialogFormVisible = false
      },
      handleSelectionChange(val) {
        this.tableSelection = val
      },
      delUsers(id) {
        let ids = []
        if (typeof(id) === 'object') {
          this.tableSelection.forEach(item => {
            ids.push(item.id)
          })
          ids = ids.join(',')
        } else {
          ids = id
        }
        if (ids === '') {
          this.$message({showClose: true, message: '请先选择一条', type: 'warning'});
          return false
        }
        this.$confirm('此操作将永久删除选择的用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUsers({ids: ids}).then(res => {
            res = res.data
            if (res.code === 200) {
//              this.resetQuery()
              this.getUserList(this.query)
              this.$message({showClose: true, message: '删除成功', type: 'success'});
            } else {
              this.$message({showClose: true, message: res.message, type: 'error'});
            }
          })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        })
      },
      submitedUser() {
        this.resetQuery()
        this.isPaging = false
        this.getUserList(this.query)
        this.$nextTick(() => {
          this.isPaging = true
        })
      },
      doSearchUsers() {
        clearTimeout(this.saveSetTimeoutSearch)
        this.saveSetTimeoutSearch = setTimeout(() => {
          this.getUserList(this.query)
        }, 500)
      },
      submitedPassword() {

      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped="scope">
  .myOrgTreeSelection /deep/ {
    .vue-treeselect__control {
      height: 28px !important;
      .vue-treeselect__placeholder, .vue-treeselect__single-value {
        line-height: 29px;
        font-size: 13.33333px;
        font-family: Arial;
      }
    }
    .vue-treeselect__menu {
      color: #606266;
      font-size: 14px;
      overflow: auto !important;
      width: 360px;
    }
  }

  .el-header, .el-footer {
    background-color: #B3C0D1;
    color: #333;
    text-align: center;
    line-height: 60px;
  }

  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    line-height: 200px;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
    line-height: 160px;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }

  .el-header {
    background: #fff;
  }

  .el-main {
    background: #fff;
  }


</style>
